using AutoMapper;
using B.S.NewMedical.Api.Read.Application.Command.ContentManagement.Patient;
using B.S.NewMedical.Api.Read.DTOS.Patient;
using B.S.NewMedical.Domain.Hospital;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Read.Application.Handler.ContentManagement.Patient
{
    /// <summary>
    /// 根据用户ID获取患者列表处理器
    /// </summary>
    public class GetPatientsByAccountIdHandler : IRequestHandler<GetPatientsByAccountIdCommand, ApiResult<List<PatientDisplayDto>>>
    {
        private readonly IBaseRepository<PatientModel> _patientRepository;
        private readonly ILogger<GetPatientsByAccountIdHandler> _logger;
        private readonly IMapper _mapper;

        public GetPatientsByAccountIdHandler(
            IBaseRepository<PatientModel> patientRepository,
            ILogger<GetPatientsByAccountIdHandler> logger,
            IMapper mapper)
        {
            _patientRepository = patientRepository ?? throw new ArgumentNullException(nameof(patientRepository));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
            _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
        }

        /// <summary>
        /// 处理根据用户ID获取患者列表请求
        /// </summary>
        public async Task<ApiResult<List<PatientDisplayDto>>> Handle(GetPatientsByAccountIdCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始查询用户的患者列表，用户ID：{AccountId}，包含已删除：{IncludeDeleted}", request.AccountId, request.IncludeDeleted);

                // 根据AccountId查询患者列表
                var query = _patientRepository.GetAll()
                    .Where(p => p.AccountId == request.AccountId);

                // 是否包含已删除的患者
                if (!request.IncludeDeleted)
                {
                    query = query.Where(p => !p.IsDeleted);
                }

                // 按创建时间倒序排列
                var patients = query.OrderByDescending(p => p.CreateTime).ToList();

                if (!patients.Any())
                {
                    _logger.LogInformation("未找到用户ID为 {AccountId} 的患者信息", request.AccountId);
                    return new ApiResult<List<PatientDisplayDto>>
                    {
                        Code = ApiEnum.Success,
                        Msg = "暂无患者信息",
                        Data = new List<PatientDisplayDto>()
                    };
                }

                // 映射为DTO列表
                var patientDtos = _mapper.Map<List<PatientDisplayDto>>(patients);

                _logger.LogInformation("查询用户患者列表成功，用户ID：{AccountId}，患者数量：{Count}", 
                    request.AccountId, patientDtos.Count);

                return new ApiResult<List<PatientDisplayDto>>
                {
                    Code = ApiEnum.Success,
                    Msg = "查询成功",
                    Data = patientDtos
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询用户患者列表时发生错误，用户ID：{AccountId}", request.AccountId);
                return new ApiResult<List<PatientDisplayDto>>
                {
                    Code = ApiEnum.Error,
                    Msg = "查询失败",
                    Data = new List<PatientDisplayDto>()
                };
            }
        }
    }
}